import request from './request'

// 商品信息
export interface Product {
  id: number
  name: string
  subtitle?: string
  description: string
  price: number
  originalPrice?: number
  marketPrice?: number
  image: string
  mainImage?: string
  images?: string[]
  categoryId: number
  category?: {
    id: number
    name: string
  }
  stock: number
  stockQuantity?: number
  sales: number
  status: 'active' | 'inactive'
  createdAt: string
  updatedAt: string
  isNew?: boolean
  isHot?: boolean
  isRecommend?: boolean
  keywords?: string
  unit?: string
  specifications?: Record<string, any>
  serviceInfo?: string
  shippingInfo?: string
  skus?: ProductSku[]
}

// 商品SKU信息
export interface ProductSku {
  id: number
  productId: number
  specifications: Record<string, any>
  price: number
  stockQuantity: number
  image?: string
  status: 'active' | 'inactive'
}

// 商品分类
export interface Category {
  id: number
  name: string
  description?: string
  image?: string
  parentId?: number
  children?: Category[]
}

// 商品查询参数
export interface ProductQuery {
  page?: number
  limit?: number
  categoryId?: number
  keyword?: string
  minPrice?: number
  maxPrice?: number
  sortBy?: 'price' | 'sales' | 'createdAt'
  sortOrder?: 'asc' | 'desc'
  isNew?: number
  isHot?: number
  isRecommend?: number
}

// 后端API响应结构
export interface ProductListResponse {
  list: Product[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export const productApi = {
  // 获取商品列表
  getProducts: (params?: ProductQuery) => {
    return request.get<ProductListResponse>('/api/products', { params })
  },

  // 获取商品详情
  getProductById: (id: number) => {
    return request.get<Product>(`/api/products/${id}`)
  },

  // 获取商品分类
  getCategories: () => {
    return request.get<Category[]>('/api/categories')
  },

  // 获取热门商品
  getHotProducts: async (limit = 10) => {
    const response = await request.get<ProductListResponse>('/api/products', { params: { isHot: 1, limit } })
    // 转换为兼容的响应格式，将list转换为products
    return {
      ...response,
      data: response.data?.list || []
    }
  },

  // 获取推荐商品
  getRecommendedProducts: async (limit = 10) => {
    const response = await request.get<ProductListResponse>('/api/products', { params: { isRecommend: 1, limit } })
    // 转换为兼容的响应格式，将list转换为products
    return {
      ...response,
      data: response.data?.list || []
    }
  },

  // 搜索商品
  searchProducts: (keyword: string, params?: Omit<ProductQuery, 'keyword'>) => {
    return request.get<{
      products: Product[]
      total: number
      page: number
      limit: number
    }>('/api/products/search', { params: { keyword, ...params } })
  }
}